<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
		<meta name="misapplication-tap-highlight" content="no" />
		<meta name="HandheldFriendly" content="true" />
		<meta name="MobileOptimized" content="320" />
		<title>简易监控</title>
		<style>
			#video {
				border: 0px solid red;
				/* background-color: #000000; */
			}

			.button_group {
				text-align: center;
				margin-top: 10px;
			}

			.button_group a {
				font-size: 1rem;
				padding: 4px 6px;
				border: 2px solid #dddddd;
				border-radius: 20px;
				color: #000000;
				text-decoration: none;
			}

			.button_start {}

			.button_stop {}

			.button_group2 {
				display: flex;
				flex-direction: column;
				padding: 10px;
				height: 60px;
				justify-content: space-between;
			}

			.button_group2 a {
				font-size: 1rem;
				padding: 4px 6px;
				border: 2px solid #dddddd;
				border-radius: 2px;
				color: #FFFFFF;
				text-decoration: none;
				text-align: center;
				background-color: cadetblue;
			}

			#host {}
		</style>
	</head>
	<body onselectstart="return false;" style="margin: 0;padding: 0;">
		<video id="video" width="100%" height="300"></video>
		<div class="button_group">
			<a class="button_start" href="javascript:void()" onclick="startRecord();">开始录制</a>
			<a class="button_stop" href="javascript:void()" onclick="stopRecord();">停止录制</a>
			<a class="button_hide" href="javascript:void()" onclick="closePreview();">关闭画面</a>
			<a class="button_hide" href="javascript:void()" onclick="openPreview();">开启画面</a>
		</div>

		<div style="margin-top: 30px;padding-left: 10px;">视频保存地址：</div>
		<div class="button_group2">
			<input id="host" value="http://192.168.24.157:8080/dophen/saveMonitorMP4" />
			<a class="button_hide" href="javascript:void()" onclick="updateHost();">保存</a>

		</div>
		<script type="text/javascript" charset="utf-8">
			//取消浏览器的所有事件，使得active的样式在手机上正常生效
			document.addEventListener('touchstart', function() {
				return false;
			}, true);
			// 禁止选择
			document.oncontextmenu = function() {
				return false;
			};
			// H5 plus事件处理
			function plusReady() {
				// openPrivacy();
				// Android处理返回键
				plus.key.addEventListener('backbutton', function() {
					('iOS' == plus.os.name) ? plus.nativeUI.confirm('确认退出？', function(e) {
						if (e.index > 0) {
							plus.runtime.quit();
						}
					}, 'HelloH5', ['取消', '确定']): (confirm('确认退出？') && plus.runtime.quit());
				}, false);
				// 关闭启动界面
				plus.navigator.setStatusBarBackground('#D74B28');
				setTimeout(function() {
					plus.navigator.closeSplashscreen();
				}, 200);
			}
			if (window.plus) {
				plusReady();
			} else {
				document.addEventListener('plusready', plusReady, false);
			}

			//-------------------------------------------------------------------
			let video = document.getElementById("video");
			let chunks = [];
			let mediaRecorder = null;
			let uploadUrl = document.getElementById("host").value;

			// 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
			if (navigator.mediaDevices === undefined) {
				navigator.mediaDevices = {};
			}

			// 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
			// 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
			if (navigator.mediaDevices.getUserMedia === undefined) {
				navigator.mediaDevices.getUserMedia = function(constraints) {

					// 首先，如果有getUserMedia的话，就获得它
					var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

					// 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
					if (!getUserMedia) {
						return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
					}

					// 否则，为老的navigator.getUserMedia方法包裹一个Promise
					return new Promise(function(resolve, reject) {
						getUserMedia.call(navigator, constraints, resolve, reject);
					});
				}
			}

			let constraints = {
				audio: true,
				video: {
					facingMode: {
						exact: "environment"
					},
					with: 1280,
					height: 720
				}
			};
			navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
				// 旧的浏览器可能没有srcObject
				if ("srcObject" in video) {
					video.srcObject = stream;
				} else {
					// 防止在新的浏览器里使用它，应为它已经不再支持了
					video.src = window.URL.createObjectURL(stream);
				}
				video.onloadedmetadata = function(e) {
					// video.play();
				};

				mediaRecorder = new MediaRecorder(stream);
				mediaRecorder.ondataavailable = (e) => {
					if (e.data.size > 0) {
						chunks.push(e.data);

						//当达到60片的时候，进行一次保存
						if (chunks.length >= 60) {
							saveMp4();
						}
					}
				};
			}).catch(function(err) {
				console.log(err.name + ": " + err);
			});

			function updateHost() {
				uploadUrl = document.getElementById("host").value;
				plus.nativeUI.toast("保存成功");
			}


			function startRecord() {
				if (mediaRecorder.state == "inactive") {
					mediaRecorder.start(1000);
				} else if (mediaRecorder.state == "paused") {
					mediaRecorder.resume();
				}

				video.play();
				plus.nativeUI.toast("录制中");
			}

			function stopRecord() {
				plus.nativeUI.toast("录制结束");
				//video.srcObject.getTracks().forEach((track) => track.stop());
				mediaRecorder.pause();
				video.pause();

				const blob = new Blob(chunks, {
					type: "video/mp4;codecs=h264,aac"
				});
				//const audioURL = URL.createObjectURL(blob); 
				saveMp4();
			}

			function closePreview() {
				video.load();
			}

			function openPreview() {
				video.play();
			}

			function saveMp4() {
				let subChunks = chunks.slice(0, chunks.length - 1);
				chunks = [];
				const blob = new Blob(subChunks, {
					type: "video/mp4;codecs=h264,aac"
				});
				let formaData = new FormData();
				formaData.append("file", blob, "video.mp4");
				fetch(uploadUrl, {
						method: "POST",
						body: formaData
					}).then(response => response.text())
					.then(data => console.log(data))
					.catch(error => console.error(error));
			}
		</script>
	</body>
</html>